package com.xzlf.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {
    TankJoinMsg tankJoinMsg;

    public Client(TankJoinMsg tankJoinMsg) {
        this.tankJoinMsg = tankJoinMsg;
    }

    public void connect() {
        EventLoopGroup group = new NioEventLoopGroup(3);
        Bootstrap bootstrap = new Bootstrap();
        try {
            ChannelFuture future = bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MsgDecoder());
                            pipeline.addLast(new MsgEncoder());
                            pipeline.addLast(new ClientHanler());
                        }
                    })
                    .connect("localhost", 8888)
                    .sync();
//            Channel channel = future.channel();
            System.out.println("connect to Server");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }
    }

    class ClientHanler extends SimpleChannelInboundHandler<Msg>{

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(tankJoinMsg);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Msg msg) throws Exception {
            msg.handle();
        }
    }
}
